import React, {Component} from 'react';
import './index.less';
import {connect} from 'src/hrpub/common/store';
// 引入 ECharts 主模块
import echarts from 'echarts/lib/echarts';
// 引入饼形图
import 'echarts/lib/chart/pie';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
// 引入图例
import 'echarts/lib/component/legend';
import {base} from 'nc-lightapp-front';
import {MyMonthPicker} from "../../../../../../public/components/MyDatePicker"
import moment from 'moment';
import {COMMON} from "../../../../unit/util";
import main from "../../../../../../turn_positive/turn_positive/actions/main";

class Echarts extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dateValue: null,
        };
    }

    componentWillReceiveProps(nextProps, nextContext) {
        if (nextProps.pk_org !== this.props.pk_org || nextProps.pk_psncl !== this.props.pk_psncl) {
            this.getChartData(nextProps);
        }
    }

    componentDidMount() {
        let curTime = new Date();
        let month = curTime.getMonth() + 1;
        if (month < 10) {
            month = '0' + month;
        }
        let dateValue = curTime.getFullYear() + '-' + month;
        this.setState({
            dateValue
        });
        setTimeout(this.drawChart, 100)
    }

    drawChart = () => {
        // 基于准备好的dom，初始化echarts实例
        this.myChart = echarts.init(document.getElementById('staff-change'));
        //  请求数据后 在初始化chart
        this.getChartData(this.props);
    };

    /**
     * 获取图表数据
     * @returns {Promise<void>}
     */
    getChartData = async (props) => {
        let month, year;
        let dateVal = (this.state.dateValue && this.state.dateValue._d) || (new Date());
        month = dateVal.getMonth() + 1 + '';
        year = dateVal.getFullYear() + '';
        let postData = {
            month,
            year,
            pk_org: props.pk_org,
            pk_psncl: props.pk_psncl
        };
        let res = await props.dispatch({
            type: 'staffCom/queryStaffChange',
            payload: {
                postData
            }
        });
        if (!res.success) return;
        this.formatData(res);
    };

    /**
     * 处理返回数据
     * @param res
     */
    formatData = (res) => {
        let data = [];
        res.data.forEach(function (item) {
            //if(item.cnt){
            data.push({
                name: item.trnstypename,
                value: item.cnt
            });
        });
        let option = this.getOption(data);
        // 绘制图表
        this.myChart.setOption(option);
    };

    /**
     *
     * @param data [
     { value: 1, name: '晋升' },
     { value: 2, name: '组织变更' },
     { value: 3, name: '工作地变更' },
     { value: 4, name: '岗位变更' }
     ]
     * @returns
     */
    getOption(data) {
        let hideZeroFlag = false;
        if (data) {
            for (let i = 0; i < data.length; i++) {
                let tempData = data[i];
                if (tempData['value']) {
                    let dataVal = tempData['value'] - 0;
                    if (dataVal !== 0) {
                        hideZeroFlag = true;
                        break
                    }
                }
            }
        }
        return {
            tooltip: {
                trigger: 'item',
                formatter: "{b}: {c} ({d}%)"
            },
            legend: {
                orient: 'vertical',
                left: 'right',
                align: 'left',
                selectedMode: false,
                data: data,
                textStyle: {
                    color: "#999"
                }
            },
            color: ['#30c5f7', '#ff6d2d', '#fcc009', '#8688f7', '#21c77f'],//'#ff7f50','#87cefa','#da70d6','#32cd32','#6495ed','#ff69b4','#ba55d3','#cd5c5c','#ffa500','#40e0d0','#1e90ff','#ff6347','#7b68ee','#00fa9a','#ffd700','#6699FF','#ff6666','#3cb371','#b8860b','#30e0e0'
            series: [{
                name: this.props.staffCom.language['变动类型'],
                type: 'pie',
                radius: ['50%', '70%'],
                center: ['38%', '50%'],
                avoidLabelOverlap: false,
                connectNulls: false,
                label: {
                    normal: {
                        show: true,
                        position: 'outside',
                        textStyle: {
                            fontSize: '20'
                        },
                        formatter: function (val) {
                            let valData = val.value - 0;

                            // 如果valData的值为0 且其他值不为0 则返回 “”   如果其他值都为0则返回0
                            if (valData === 0 && hideZeroFlag) {
                                return '';
                            }

                            return valData + ''
                        }
                    },
                    emphasis: {
                        show: true,
                        textStyle: {
                            fontSize: '20',
                            fontWeight: 'bold'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                // data: [
                //     { value: 1, name: '晋升' },
                //     { value: 2, name: '组织变更' },
                //     { value: 3, name: '工作地变更' },
                //     { value: 4, name: '岗位变更' }
                // ]
                data: data
            }]
        };
    }

    onChange = (date) => {
        this.setState({
            dateValue: date
        }, () => {
            this.getChartData(this.props);
        })
    };

    clickMore = () => {
        this.props.showDetail(COMMON.pageStaffChange);
        let mainDate = this.state.dateValue;
        if (mainDate.hasOwnProperty("_d")) {
            let curDate = mainDate._d;
            mainDate = curDate.getFullYear() + '-' + (curDate.getMonth() + 1);
        }
        this.props.dispatch({
            type: 'staffCom/update',
            payload: {
                mainDate
            }
        })
    };

    render() {
        const {staffCom} = this.props;
        return (
            <div className={'staff-change-echarts'}>
                <div className={`chart-title  ${this.props.titleClass}`}>
                    <div className={`title-name ${this.props.titleClass}`}>
                        {staffCom.language["gx6008-000183"]}
                    </div>
                    <div className={'more'} onClick={() => {
                        this.clickMore();
                    }}>
                    </div>
                </div>
                <div className={"chart-content"}>
                    <div className={'date'}>
                        <MyMonthPicker
                            format={"YYYY-MM"}
                            defaultValue={moment()}
                            onChange={this.onChange}
                            // showToday={true}
                        />
                    </div>
                    <div id="staff-change">

                    </div>
                </div>
            </div>
        );
    }
}

export default Echarts;
